<template>
  <view>
    <l-background has-sub-background />
	<view class="details-tag">
		<block v-for="(item,index) in tag" :key="index">
			<view :class="currenTag == index? 'tag tag-choose':'tag'" @click="tagChange(index)">
				{{item.title}}
			</view>
		</block>
	</view>
	
	<swiper :current="currenTag" class="conten-swiper" @change="handleSwiperChange">
		<swiper-item class="conten-swiper-sc">
			<scroll-view :scroll-y="true" class="conten-scroll" :style="{height: swiperHeight + 'px'}" >
				<view class="padding-30">
				  <view class="card">
				    <l-form-cell
				      v-for="(item,index) in formList"
				      :key="index"
				      v-model="form[item.attr]"
				      :label="item.label || item.placeholder"
				      :must="item.must"
				      :maxlength="item.maxlength"
				      :has-slot="item.hasSlot"
				      :arrow="item.hasSlot"
				      :placeholder="'请输入' + item.placeholder"
				      :unlined="index === formList.length-1"
				      :suffix="item.suffix"
				      @click="changeDate(item)"
				    >
				      <view class="form-item flex-row form-item justify-end align-center">
				        <text class="text-30" :class="['color-t' + (form[item.attr] ? 1 : 3)]">{{ form[item.attr] || item.toast }}</text>
				      </view>
				    </l-form-cell>
				  </view>
				
				  <view class="repair-conten">
				  	<!-- 备注 -->
				  	<view class="repair-remarks">
				  		<view class="remarks-title">备注</view>
				  		<view class="remarks-conten" style="margin: 10rpx;">
							<view style="width: 100%;">
								<textarea class="remarks-text" :maxlength="100" @input="commentFn" name="comment" auto-height="true" v-model="form.comment" placeholder="请输入备注"></textarea>
							</view>
				  		</view>
				  	</view>
				  	
				  </view>
				
				  <view class="card padding-30 margin-top-30">
				    <text class="text-30 color-t1">维修图片</text>
				
				    <tui-upload
				      :value="imgList"
				      :icon-size="60"
				      :row="4"
				      :limit="6"
				      width="146"
				      height="146"
				      dir="vehicle"
				      margin="20rpx 15rpx 0 0"
				      @chooseImage="chooseImage"
				      @remove="removeImage"
				    />
				  </view>
				</view>
			</scroll-view>
		</swiper-item>
		<swiper-item class="conten-swiper-sc">
			<scroll-view :scroll-y="true" class="conten-scroll" :style="{height: swiperHeight + 'px'}" >
				<block v-if="form.items.length > 0">
					<view class="repair-fee-list">
						<block v-for="(item,index) in form.items" :key="index">
							<view class="repair-info">
								<view class="info-list" v-for="(item_s,index_s) in objDataList" @click="toExpense(true,item,index)" :key="index_s">
									<view class="info-name">
										{{item_s.titele}}
									</view>
									<view class="info-conten">
										{{item[item_s.objName] || ''}}
									</view>
								</view>
								<span style="display: inline-block;border: 2rpx solid #f3f3f3;margin: 10rpx 0prx;width: 96%;margin-left: 2%;"></span>
								<view class="removeDiv">
									<view class="removeBtn" @click="removeExpense(index)">
										删除
									</view>
								</view>
							</view>
						</block>
					</view>
					
				</block>
				<block v-else>
					<view class="repair-info" style="text-align: center;">
						暂无数据
					</view>
				</block>
			</scroll-view>
		</swiper-item>
	</swiper>
	
    <bz-date-picker :value="start" :days="92" :min-time="minStartDate" type="start" :default-time="startDate" :minute-step="10" @confirm="startDateConfirm" @cancel="close('start')" @close="close('start')" />
    <bz-date-picker v-if="endTimeShow" :value="end" :days="92" :min-time="form.startDate.replace(/-/g,'/') || minStartDate" type="end" :default-time="endDate" :minute-step="10" @confirm="endDateConfirm" @cancel="close('end')" @close="close('end')" />

    <!-- <l-bottom-button text="确认" @click="submit" /> -->
	<view class="fixed-btn">
		<view class="add-expense" @click="toExpense(false)">
			添加费用
		</view>
		<view class="btn-submit" @click="submit">
			保存
		</view>
	</view>
  </view>
</template>

<script>
import { getExpense } from '../api'
import { formVerify, dateFormat, checkDate } from '@/common/util'
import { editRepair, addRepair } from '../api'
export default {
  name: 'AddMaintenancePlan',
  data() {
    const today = new Date()
    const tomorrow = today.getTime() + (1000 * 60 * 60 * 24)

    const date = new Date(tomorrow)
    date.setMinutes(0)
    const start = date.setHours(6)
    const end = date.setHours(21)

    const minStart = new Date(today.setDate(today.getDate() - 30))
    minStart.setHours(0)
    minStart.setMinutes(0)
    const minStartDate = dateFormat(minStart, 'YYYY/MM/DD hh:mm')
    const startDate = dateFormat(new Date(start), 'YYYY/MM/DD hh:mm')
    const endDate = dateFormat(new Date(end), 'YYYY/MM/DD hh:mm')
    return {
	  swiperHeight: 600,
      form: {
        id: '',
        repairFee: '',
        repairAddress: '',
        repairContent: '',
        startDate: '',
        endDate: '',
        status: 2,
        repairImage: '',
        vehicleId: '',
		comment:'',
		items:[],
		currentMileage:''
      },
      formList: [
        { attr: 'startDate', label: '送修时间', toast: '请选择送修时间', must: true, hasSlot: true },
        { attr: 'endDate', label: '取回时间', toast: '请选择取回时间', must: true, hasSlot: true },
        { attr: 'repairContent', placeholder: '维修内容', maxlength: 100, type: 'text', must: true, hasSlot: false },
        { attr: 'repairAddress', placeholder: '维修厂', maxlength: 100, type: 'text', must: true, hasSlot: false },//
		{ attr: 'sendRepairName', placeholder: '送修人', maxlength: 30, type: 'text', must: false, hasSlot: false },
		{ attr: 'currentMileage', placeholder: '当前里程', maxlength: 6, type: 'text', must: false, hasSlot: false },
        // { attr: 'repairFee', placeholder: '维修费用', maxlength: -1, type: 'digit', must: true, hasSlot: false, suffix: '元' }
      ],
	  objDataList:[{
	  	titele:'维修项目',
	  	objName:'itemName',
	  },{
	  	titele:'配件供应商',
	  	objName:'partsSupplier',
	  },{
	  	titele:'配件名称',
	  	objName:'partsName',
	  },{
	  	titele:'规格',
	  	objName:'specifications',
	  },{
	  	titele:'材料费',
	  	objName:'materialsFee',
	  },{
	  	titele:'工时费',
	  	objName:'workHoursFee',
	  },{
	  	titele:'备注',
	  	objName:'comment',
	  }],
	  tag:[{title:'维修详情'},{title:'费用信息'}],
	  currenTag:0,
      set: '',
      imgList: [],
      minStartDate,
      startDate,
      endDate,
      start: false,
      end: false,
      endTimeShow: false,
	  id:''
    }
  },
  onLoad(e) {
    if (e.vehicleId) this.form.vehicleId = e.vehicleId
    else this.init(e.item)
	
	this.initSwiperHeight();
  },
  onShow() {
  	this.getItems()
  },
  methods: {
	  commentFn(e){
		  var value = e.detail.value;
			  var len = parseInt(value.length);
			  if(len > 100){
				  value = value.substring(0,500)
			  }
		      this.form.comment = value
	  },
	  initSwiperHeight() {
		uni.getSystemInfo({ 
		  success: (res) => {
			this.swiperHeight = res.windowHeight - 46 - 82;
		  }
		})
	  },
	  getList(){
	  	let _then = this
	  	 getExpense(this.id).then(res=>{
	  		 _then.form = res[1].data.data
			 _then.form.id = _then.id
	  		 _then.imgList = _then.form.repairImage.split(',')
	  	 })
	  },
	  isNumber(val){
	  	var regPos = /[^0-9.]/g; //判断是否是数字。
	  	if(regPos.test(val) ){
	  		return false;
	  	}else{
	  		return true;
	  	}
	  },
	  getItems(){
		  let _than = this
		  try{
		  	uni.getStorage({
		  		key:'itemName',
		  		success(res){
		  			console.log('数据获取成功')
		  			let formDtas = res.data;
		  			if(formDtas.flag == false){
		  				_than.form.items[formDtas.index] = formDtas.object
						_than.form.items.reverse()
		  			}else{
		  				_than.form.items.push(formDtas)
						_than.form.items.reverse()
		  			}
		  		}
		  	})
		  	uni.removeStorage({
		  		key:'itemName'
		  	})  
		  }catch(e){
		  	//TODO handle the exception
		  }
	  },
	  toExpense(flag,item,index){
		  if(flag){
			  let obj = {
				  item:item,
				  index:index
			  }
			  this.jump('/vehicle/add-expense/add-expense?obj=' + JSON.stringify(obj))
			  return false
		  }
		  this.jump('/vehicle/add-expense/add-expense')
	  },
	  removeExpense(data){
		let _than = this
	  	wx.showModal({
	  	     title: '提示',
	  	     content: '是否删除该费用',
	  	     success: function (res) {
	  	       if (res.confirm) {
	  			_than.form.items.splice(data,1)
	  	       } else {
	  	         console.log('用户点击取消')
	  	       }
	  	     }
	  	   })
	  },
	  tagChange(index){
	  	this.currenTag = index
	  },
	  handleSwiperChange(e){
	  	this.currenTag = e.detail.current
	  },
    init(item) {
      const detail = JSON.parse(item)
	  this.id = detail.id
	  this.getList()
    },
    // 提交表单
    async submit() {
      if (formVerify(this.form, this.formList) && checkDate(this.form.startDate, this.form.endDate)) {
        const obj = this.copyData(this.form)
        obj.startDate = obj.startDate + ':00'
        obj.endDate = obj.endDate + ':00'
		console.log('obj')
		console.log(obj)
		if(!obj.currentMileage == ''){
			if(this.isNumber(obj.currentMileage) == false){
				uni.showToast({
				title: '里程输入有误！', // 标题
				  icon: 'error',  // 图标类型，默认success
				  duration: 1000  // 提示窗停留时间，默认1500ms
				})
				return false
			}
		}
        let api = addRepair
        if (obj.id) api = editRepair
        const [err, res] = await api(obj)
        if (!this.$http.errorCheck(err, res)) return false
        this.toast(obj.id ? '修改成功' : '添加成功', () => {
          this.jump()
        })
      }
    },
    // 修改时间
    changeDate(item) {
      if (item.hasSlot) {
        let attr = item.attr
        if (attr.includes('end') && !this.form.startDate) {
          this.toast('请选择开始时间')
        } else {
          attr = attr.slice(0, attr.indexOf('D'))
          this[attr] = true
        }
      }
    },
    // 修改开始时间
    startDateConfirm(e) {
      this.form.startDate = dateFormat(e, 'YYYY-MM-DD hh:mm')
      this.startDate = dateFormat(e, 'YYYY/MM/DD hh:mm',)
      this.endDate = dateFormat(new Date(this.startDate).setHours(new Date(this.startDate).getHours() + 11), 'YYYY/MM/DD hh:mm')
      setTimeout(() => {
        this.endTimeShow = true
      }, 100)
      this.start = false
    },
    // 修改结束时间
    endDateConfirm(e) {
      this.form.endDate = dateFormat(e, 'YYYY-MM-DD hh:mm')
      this.endDate = dateFormat(e, 'YYYY/MM/DD hh:mm')
      this.end = false
      checkDate(this.form.startDate, this.form.endDate)
    },
    // 关闭时间窗口
    close(e) {
      this[e] = false
    },
    // 删除图片
    removeImage(e) {
      this.imgList.splice(e.index, 1)
      this.form.repairImage = this.imgList.join(',')
    },
    // 选择图片
    chooseImage(e) {
      this.imgList.push(...e)
      this.form.repairImage = this.imgList.join(',')
    }
  }
}
</script>

<style scoped lang="scss">
.card{
  border-radius:20rpx;
}
			.details-tag{
				position: sticky;
				top: 0;
				left: 0;
				z-index: 100;
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				background-color: #5a5e63;
				.tag{
					padding: 20rpx;
					flex: 1;
					line-height: 40rpx;
					color: #fff;
					text-align: center;
					position: relative;
				}
				.tag-choose::after{
					content: '';
					display: inline-block;
					width: 20%;
					height: 4rpx;
					background-color: #fff;
					position: absolute;
					left: 50%;
					transform: translateX(-50%);
					bottom: 0;
				}
			}
			.conten-swiper{
				height: calc(100vh - 256rpx);
				margin-top: 10rpx;
				width: 100%;
				overflow: hidden;
				border-radius: 30rpx 30rpx 0  0;
				background-color: #f2f2f2;
				// padding: 20rpx;
				.conten-swiper-sc{
					height: calc(100vh - 90rpx);
					width: 100%;
					overflow: hidden;
					.conten-scroll{
						.remarks-text{
							letter-spacing: 4rpx;
							height:30rpx;
							box-shadow:0 10rpx 10rpx -10rpx tgba(0,0,0,.3);
							width:100%;
						}
						.repair-conten{
							width: 100%;
							padding: 20rpx;
							background-color: #fff;
							border-radius: 20rpx;
							margin-bottom: 20rpx;
							margin-top: 20rpx;
							.repair-list{
								display: flex;
								justify-content: space-between;
								align-items: center;
								line-height: 30rpx;
								font-size: 30rpx;
								position: relative;
								padding-bottom: 10rpx;
							}
							// .repair-list::after{
							// 	content: '';
							// 	width: 100%;
							// 	height: 2rpx;
							// 	background-color: #aaaaaa;
							// 	display: inline-block;
							// 	position: absolute;
							// 	left: 50%;
							// 	transform: translateX(-50%);
							// 	bottom: -15rpx;
							// }
						}
						
						.repair-fee-list {
							padding: 20rpx;
						}
						.repair-info{
							width: 100%;
							padding: 20rpx;
							background-color: #fff;
							border-radius: 20rpx;
							margin-bottom: 20rpx;
							.removeDiv{
								width: 100%;
								background-color: #fff;
								box-sizing: border-box;
								padding: 10rpx 20rpx;
								display: flex;
								justify-content: flex-end;
								align-items: center;
							}
							.removeBtn{
								padding: 20rpx 40rpx;
								line-height: 30rpx;
								text-align: center;
								border-radius: 10rpx;
								border: 1rpx solid #aaaaaa;
								}
							.info-list{
								width: 100%;
								display: flex;
								justify-content: space-between;
								align-items: center;
								line-height: 30rpx;
								font-size: 30rpx;
								position: relative;
								margin-bottom: 10rpx;
								.info-name{
									color: #aaaaaa
								}
								.info-conten{
									width: 66vw;
								}
							}
						}
					}
				}
			}
    .fixed-btn {
    	position: fixed;
    	bottom: 0px;
    	width: 100%;
    	box-sizing: border-box;
    	padding: 40rpx;
    	display: flex;
    	justify-content: space-between;
    	align-items: center;
    	background-color: #fff;
    	z-index: 100;
    }
	.add-expense {
		flex: 1;
		height: 70rpx;
		border-radius: 20rpx;
		border: 2rpx solid #dfb175;
		color: #dfb175;
		font-size: 30rpx;
		line-height: 70rpx;
		text-align: center;
		margin-right: 20rpx;
	}
	
	.btn-submit {
		flex: 1;
		line-height: 70rpx;
		height: 70rpx;
		border-radius: 20rpx;
		background-color: #dfb175;
		font-size: 30rpx;
		color: #fff;
		text-align: center;
	}
</style>
